package com.ljf.game.event;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ljf.game.WebsocketManager;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;

/**
 * 描述 :
 * <p>
 * 版本     作者     时间      内容
 * 1.0      lijinfeng       2025-05-06 15:31     create
 */
public class EventManager {

    private static boolean init = false;

    public static void init(){
        EventManager.eventHashMap.put("CREATE_ROOM",new CreateRoomEvent());
        EventManager.eventHashMap.put("JOIN_ROOM",new JoinRoomEvent());
        EventManager.eventHashMap.put("GROUP_CHAT",new GroupChatEvent());
        EventManager.eventHashMap.put("CLOSE_ROOM",new CloseRoomEvent());
        EventManager.eventHashMap.put("EXIT_ROOM",new ExitRoomEvent());
        EventManager.eventHashMap.put("ROOM_HEART_BEAT",new RoomHeartBeatEvent());
        init = true;
    }

    public static HashMap<String,AbstractEvent> eventHashMap = new HashMap<>();

    public static AbstractEvent getExecuteEvent(Event event) {
        JSONObject json = JSON.parseObject(event.getText());
        String eventClass = json.get("EVENT_CLASS").toString();
        return eventHashMap.get(eventClass);
    }

    public static void handlerEvent(WebSocketSession session, Event event) {
        if (!init){
            init();
        }
        AbstractEvent executeEvent;
        try {
            executeEvent = getExecuteEvent(event);
        } catch (Exception e) {
            e.printStackTrace();
            WebsocketManager.sendMessage(session,new HashMap<>(),"请求数据未找到对应事件，请检查");
            return;
        }

        executeEvent.run(session,event.getText());
    }

    /**
     * 构建统一格式的JSON响应
     */
    public static String buildJsonResult(HashMap<String, Object> hashMap, String message) {
        hashMap.put("RESULT_MESSAGE", message);
        return JSONObject.toJSONString(hashMap);
    }

    public static HashMap<String,Object> getResultMap(String jsonString){
        JSONObject jsonObject =  JSON.parseObject(jsonString);
        String eventId = jsonObject.get("EVENT_ID").toString();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("EVENT_ID", eventId);
        return hashMap;
    }
}
